<?php

namespace app\site\controller;


use app\common\model\ShopClearGoodsModel;
use app\common\model\ShopGoodsSkuModel;
use think\Request;

class ShopClearGoodsController extends BaseController
{

    private $goodsSkuModel;
    private $clearGoodsModel;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->clearGoodsModel = new ShopClearGoodsModel();
        $this->goodsSkuModel=new ShopGoodsSkuModel();
    }

    /**
     * 清仓商品列表
     */
    public function index(){
        $query          = $this->request->request();
        $map['site_id'] = $this->getSiteId();
        $goodsName  = $this->request->param('goods_name');
        if (!empty($goodsName)) {
            $map['goods_name'] = ['like', '%' . $goodsName . '%'];
        }
        $list = $this->clearGoodsModel->where($map)->paginate(12, false, ['query' => $query]);
        $this->assign('query', $query);
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 添加清仓商品
     */
    public function addGoods(){
        $skulist = $this->request->param('sku_list/a');
        if(empty($skulist)){
            $this->error('请选择库存商品！');
        }
        $dataList = [];
        foreach($skulist as $sku){
            if($sku['total_clear_price']>$sku['total_goods_price']){
                $this->error('清仓价必须小于商品总价!');
            }
            $skuIds[] = $sku['sku_id'];
        }
        $haveSkuids = $this->clearGoodsModel->where('sku_id','in',$skuIds)->where('site_id',$this->getSiteId())->column('sku_id');
        $insertSkuIds = $skuIds;
        if($haveSkuids){
            $insertSkuIds = array_diff($skuIds,$haveSkuids);
        }
        //去除已有数据
        foreach ($skulist as $sku){
            if(in_array($sku['sku_id'],$insertSkuIds)){
                $dataList[]=$sku;
            }
        }
        if($dataList){
            $this->goodsSkuModel->where('sku_id','in',$insertSkuIds)->setField('promotion_type',3);
            $this->clearGoodsModel->saveAll($dataList);
        }
        $this->success('操作成功！');
    }

    /**
     * 删除清仓商品
     */
    public function delGoods(){
        $clearGoodsId = $this->request->param('clear_goods_id/d');
        $skuId = $this->request->param('sku_id/d');
        $this->goodsSkuModel->where('sku_id',$skuId)->setField('promotion_type',0);
        $this->clearGoodsModel->where('clear_goods_id',$clearGoodsId)->delete();
        $this->success('操作成功！');
    }

}